<?php

namespace app\controllers;

use app\librarys\BaseController;
use app\models\Order;
use app\models\Permission;
use app\models\Report;
use PHPExcel;
use PHPExcel_IOFactory;
use PHPExcel_Style_Color;
use yii\data\Pagination;
use app\models\Institution;
use app\models\Manager;
use Yii;

/**
 * 数据报表
 * Class ReportController
 * @package app\controllers
 */
class ReportController extends BaseController
{
    public static $pageSize = 10;

    /**
     * 机构账户列表
     * @return string
     */
    public function actionInstitutionAccount()
    {
        //--获取操作用户信息，用户机构id=0为系统级管理员，可为子机构添加子机构--------
        $current_console_user = Manager::getCurrentManager();
        $institution = $current_console_user['institution_code'];
        if ($institution == '0') {
            $institutionName = '----全部机构----';
        } else {
            $institutionName = Manager::getCurrentManager()['institution_name'];
        }
        //----------------------------------------------------------------------------
        $request = \Yii::$app->request;

        $institutionCode = $request->get("institution");
        if ($institutionCode == '') {
            $institutionCode = $institution;
        }

        $total = $request->get("total");
        $ob = $request->get("ob");
        $start = $request->get("page");

        if ($start == '') {
            $start = 0;
        } else {
            $start = ($start - 1) * self::$pageSize;
        }
        if($ob=='1'){
            $orderBy='desc';
        }else{
            $orderBy='asc';
        }

        $total_page = Institution::getInstitutionAccountListTotal($total, $institutionCode);
        $record = Institution::getInstitutionAccountList($start, self::$pageSize, $total, $institutionCode, $orderBy);

        $pagination = new Pagination([
            'defaultPageSize' => self::$pageSize,
            'totalCount' => $total_page,
        ]);

        return $this->render('institution-account',
            ['current_institution_code' => $institutionCode,
                'current_institution_name' => $institutionName,
                'pagination' => $pagination,
                'record' => $record,
                'total' => $total,
                'ob' => $ob]);
    }


    /**
     * 订单报表
     * @return string
     */
    public function actionFlowList()
    {
        $institutionCode = Manager::getCurrentManager()['institution_code'];
        if ($institutionCode == '0') {
            $institutionCode = \Yii::$app->request->get('institution_code');
        }


        $start_time = \Yii::$app->request->get('start_time','');
        $end_time = \Yii::$app->request->get('end_time','');
        $origin_code = \Yii::$app->request->get('origin_code','');
        $start_time_exe=$start_time;

        if(empty($start_time)){
            $start_time_exe='1970-01-01';
        }
        $end_time_exe=$end_time;
        if(empty($end_time)){
            $end_time_exe='2050-12-31';
        }
        $pageSize = 10;
        $totalCount = Report::getFlowList2($institutionCode, 0, 0, $start_time_exe, $end_time_exe, $origin_code, 'count');

        $pagination = new Pagination([
            'defaultPageSize' => $pageSize,
            'totalCount' => $totalCount,
        ]);

        $items = Report::getFlowList2($institutionCode, $pagination->offset, $pagination->limit, $start_time_exe, $end_time_exe, $origin_code, 'list');

        $accountRecordSum = Report::getSumInstitutionAccountRecordSum($institutionCode, $origin_code, $start_time_exe, $end_time_exe);
        return $this->render('flow-list',
            [
                'items' => $items,
                'pagination' => $pagination,
                'totalCount' => $totalCount,
                'current_institution_code' => $institutionCode,
                'origin_code' => $origin_code,
                'start_time' => $start_time,
                'end_time' => $end_time,
                'accountRecordSum' => $accountRecordSum,
            ]);
    }

    /**
     * 流转订单详情
     * @return string
     */
    public function actionOrderFlowDetailPartial()
    {

        $order_code = \Yii::$app->request->post('order_code');
        $institution_code = \Yii::$app->request->post('institution_code');
        $orderFlowId=Report::getOrderFlowByOrderCode($institution_code,$order_code)['id'];

        $item = Order::getFlowDetail($orderFlowId);

        $orderItem = Order::getDetailByCode($item['order_code']);

        //退货信息
        $institution_code = '';
        if (!Permission::isSystemAdmin()) {
            $institution_code = $item['institution_code'];
        }

        $institution_code=Report::getBackGoodsRecord_institutionCode($item['order_code']);
        $backGoodsItems = Order::getBackGoodsRecordForFlow($item['order_code'], $institution_code);

        return $this->renderPartial('order-flow-detail-partial',
            [
                'item' => $item,
                'orderItem' => $orderItem,
                'backGoodsItems' => $backGoodsItems
            ]);
    }

    /**
     * 导出订单报表
     * export-flow-list
     */
    public function actionExportFlowList()
    {
        $institutionCode = Manager::getCurrentManager()['institution_code'];
        if ($institutionCode == '0') {
            $institutionCode = \Yii::$app->request->get('institution_code');
        }

        $start_time = \Yii::$app->request->get('start_time','');
        $end_time = \Yii::$app->request->get('end_time','');
        $origin_code = \Yii::$app->request->get('origin_code','');
        $start_time_exe=$start_time;
        if(empty($start_time)){
            $start_time_exe='1970-01-01';
        }
        $end_time_exe=$end_time;
        if(empty($end_time)){
            $end_time_exe='2050-12-31';
        }
        $objPHPExcel = new PHPExcel();
        //标题栏
        $i = 1;
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $i, '订单号');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, '订单时间');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $i, '产品代码');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $i, '产品名称');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $i, '产品数量');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F' . $i, '结算单价');
//        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G' . $i, '现金支付');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H' . $i, '总价');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I' . $i, '积分单价');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J' . $i, '积分总价');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('K' . $i, '收货人姓名');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('L' . $i, '省份');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('M' . $i, '市');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('N' . $i, '区');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('O' . $i, '详细地址');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('P' . $i, '手机号码');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('Q' . $i, '邮政编码');
        $objPHPExcel->setActiveSheetIndex(0)->setCellValue('R' . $i, '订单备注');

        $items = Report::getFlowList2($institutionCode, 0, 9999999, $start_time_exe, $end_time_exe, $origin_code, 'export');
        foreach ($items as $item) {
            $orderCode = $item['t1'];
            $pay_price=$item['t4'];
//            $i++;
//            $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $i, $orderCode);
//            continue;
            //获取用户订单信息
            $integral_rate = Institution::getInstitutionInfo($institutionCode)['integral_rate'];
            $orderList = Report::getUserOrderInfo($orderCode, $institutionCode);
            foreach ($orderList as $orderItem) {
                $i++;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $i, $orderCode);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, $orderItem['create_datetime']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $i, $orderItem['goods_code']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $i, $orderItem['goods_name']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $i, $orderItem['quantity']);

                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F' . $i, $orderItem['settlement_price']);
//                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('G' . $i, $pay_price);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H' . $i, $orderItem['settlement_price'] * $orderItem['quantity']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I' . $i, $orderItem['selling_price'] * $integral_rate);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('J' . $i, $orderItem['selling_price'] * $orderItem['quantity'] * $integral_rate);

                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('K' . $i, $orderItem['receiver_name']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('L' . $i, $orderItem['receiver_province']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('M' . $i, $orderItem['receiver_city']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('N' . $i, $orderItem['receiver_region']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('O' . $i, $orderItem['receiver_address']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('P' . $i, $orderItem['receiver_phone']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('Q' . $i, $orderItem['receiver_postcode']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('R' . $i, $orderItem['receiver_remark']);
            }
            //获取用户退单信息
            $backList = Report::getBackGoodsRecord($orderCode);
            foreach ($backList as $orderItem) {
                $i++;
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('A' . $i, $orderCode);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('B' . $i, $orderItem['create_datetime']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('C' . $i, $orderItem['goods_code']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('D' . $i, $orderItem['goods_name']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('E' . $i, $orderItem['quantity']);

                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('F' . $i, -$orderItem['settlement_price']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('H' . $i, -$orderItem['settlement_price'] * $orderItem['quantity']);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('I' . $i, -$orderItem['selling_price'] * $integral_rate);
                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('Q' . $i, -$orderItem['selling_price'] * $orderItem['quantity'] * $integral_rate);


                $objPHPExcel->setActiveSheetIndex(0)->setCellValue('R' . $i, '退单');
                $objPHPExcel->setActiveSheetIndex(0)->getStyle("A$i:Q$i")->getFont()->getColor()->setARGB(PHPExcel_Style_Color::COLOR_RED);
            }
        }


        $filename = "order-$institutionCode-$start_time-$end_time.xls";
        // Redirect output to a client’s web browser (Excel5)
        header('Content-Type: application/vnd.ms-excel');
        header('Content-Disposition: attachment;filename="' . $filename . '"');
        header('Cache-Control: max-age=0');
// If you're serving to IE 9, then the following may be needed
        header('Cache-Control: max-age=1');
// If you're serving to IE over SSL, then the following may be needed
        header('Expires: Mon, 26 Jul 1997 05:00:00 GMT'); // Date in the past
        header('Last-Modified: ' . gmdate('D, d M Y H:i:s') . ' GMT'); // always modified
        header('Cache-Control: cache, must-revalidate'); // HTTP/1.1
        header('Pragma: public'); // HTTP/1.0

        $objWriter = PHPExcel_IOFactory::createWriter($objPHPExcel, 'Excel5');
        $objWriter->save('php://output');
        exit;
    }
}